package modules.loan.controller;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import modules.loan.entity.Loan;
import modules.loan.entity.LoanRepayment;
import modules.loan.service.LoanService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/loanController")
public class LoanController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoanController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private LoanService loanService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/loan/loan-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param loan
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Loan loan, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Loan.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, loan, request.getParameterMap());
			cq.add();
			loanService.listByPage(cq, true);
			dataGrid.setFooter(
					"principal,interest,totalAmount,realPrincipal,realInterest,realTotalAmount,oweAmount,period:合计");
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("到期还款查询失败", e);
			throw new BusinessException("到期还款查询失败", e);
		}
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(Loan loan, HttpServletRequest req) {
		if (StringUtils.isNotBlank(loan.getId())) {
			loan = loanService.get(Loan.class, loan.getId());
			req.setAttribute("loanPage", loan);
		}
		return new ModelAndView("modules/loan/loan-update");
	}

	/**
	 * 还款页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goRepayment")
	public ModelAndView goRepayment(Loan loan, HttpServletRequest req) {
		if (StringUtils.isNotBlank(loan.getId())) {
			loan = loanService.get(Loan.class, loan.getId());
			BigDecimal owePrincipal = loan.getPrincipal().subtract(loan.getRealPrincipal());
			BigDecimal oweInterest = loan.getInterest().subtract(loan.getRealInterest());
			req.setAttribute("owePrincipal", owePrincipal);
			req.setAttribute("oweInterest", oweInterest);
			req.setAttribute("loanPage", loan);
		}
		return new ModelAndView("modules/loan/loan-repayment");
	}

	/**
	 * 修改
	 * 
	 * @param loan
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(Loan loan, HttpServletRequest request) {
		String msg = null;
		try {
			loan = loanService.get(Loan.class, loan.getId());
			BigDecimal interest = new BigDecimal(request.getParameter("interest"));
			loan.setInterest(interest);
			loan.setTotalAmount(loan.getPrincipal().add(loan.getInterest()));
			if (loan.getRealTotalAmount().compareTo(loan.getTotalAmount()) >= 0) {
				// 如果实还总额大于应还总额,则尚欠金额为0,状态为已还清
				loan.setOweAmount(new BigDecimal(0));
				loan.setStatus(Loan.STATUS_YES);
			} else {
				loan.setOweAmount(loan.getTotalAmount().subtract(loan.getRealTotalAmount()));
				if (loan.getRealTotalAmount().compareTo(new BigDecimal(0)) == 0) {
					// 如果实还总额等于0
					loan.setStatus(Loan.STATUS_NO);
				} else {
					loan.setStatus(Loan.STATUS_ING);
				}
			}

			loanService.update(loan);
			msg = "借款\"" + loan.getSn() + "\"修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "借款\"" + loan.getSn() + "\"修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 还款
	 * 
	 * @param loan
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doRepayment")
	@ResponseBody
	public Result doRepayment(Loan loan, HttpServletRequest request) {
		String msg = null;
		try {
			loan = loanService.get(Loan.class, loan.getId());
			BigDecimal repaymentPrincipal = new BigDecimal(request.getParameter("repaymentPrincipal"));
			BigDecimal repaymentInterest = new BigDecimal(0);
			if (StringUtils.isNotBlank(request.getParameter("repaymentInterest"))) {
				repaymentInterest = new BigDecimal(request.getParameter("repaymentInterest"));
			}
			loan.setRealPrincipal(loan.getRealPrincipal().add(repaymentPrincipal));
			loan.setRealInterest(loan.getRealInterest().add(repaymentInterest));
			loan.setRealTotalAmount(loan.getRealTotalAmount().add(repaymentPrincipal).add(repaymentInterest));
			if (loan.getRealTotalAmount().compareTo(loan.getTotalAmount()) >= 0) {
				// 如果实还总额大于应还总额,则尚欠金额为0,状态为已还清
				loan.setOweAmount(new BigDecimal(0));
				loan.setStatus(Loan.STATUS_YES);
			} else {
				loan.setOweAmount(loan.getTotalAmount().subtract(loan.getRealTotalAmount()));
				loan.setStatus(Loan.STATUS_ING);
			}
			/** 还款记录 */
			LoanRepayment loanRepayment = new LoanRepayment();
			loanRepayment.setPrincipal(repaymentPrincipal);
			loanRepayment.setInterest(repaymentInterest);
			loanRepayment.setTotalAmount(repaymentPrincipal.add(repaymentInterest));
			loanRepayment.setStatus(LoanRepayment.STATUS_ENABLE);

			loanService.repayment(loan, loanRepayment);
			msg = "借款\"" + loan.getSn() + "\"还款成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "借款\"" + loan.getSn() + "\"还款失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

}
